<!-- 模板区域：定义用户界面结构 -->
<template>
  <div class="image-annotation">
    <!-- 控制面板：提供形状选择按钮和缩放控制 -->
    <div class="control-panel">
      <!-- 形状选择按钮 -->
      <button @click="addRectangle()">矩形</button>
      <button @click="addCircle()">圆形</button>
      <button @click="addLine()">线</button>
      <button @click="addPoint()">点</button>
      <button @click="addPolygon()">多边形</button>
      <!-- 缩放控制按钮 -->
      <button @click="originalSize">原始尺寸</button>
      <button @click="fitToCanvas">适应比例</button>
      <button @click="addRectangleList">绘制矩形群体</button>

      <div class="scale-controls">
        <button @click="decreaseScale">-</button>
        <span>{{ (scaleNum * 100).toFixed(0) }}%</span>
        <!-- 显示当前缩放比例 -->
        <button @click="increaseScale">+</button>
      </div>
    </div>
    <!-- 绘图画布 -->
    <canvas id="myCanvas" width="1200" height="800"></canvas>
  </div>
</template>

<!-- <script>
export default {
  data() {
    return {
      canvas: null,
      scaleNum: 1, // 初始缩放比例为100%
      selectedShape: null, // 当前选中的绘制形状类型
      shapes: [], // 存储所有绘制的形状数据
      imgSrc:
        "https://file.51pptmoban.com/d/file/2024/07/28/4b668a6fd46160f0a90ccbc9c4f31adc.jpg", // 图像源路径，请替换为实际图片URL
      imgX: 600, // 图像中心点 X 坐标（默认居中）
      imgY: 400, // 图像中心点 Y 坐标（默认居中）
      canvasWidth: 1200, // 画布宽度
      canvasHeight: 800, // 画布高度
      isDragging: false, // 标记是否正在拖拽
      dragStartX: 0, // 拖拽开始时的鼠标 X 坐标
      dragStartY: 0, // 拖拽开始时的鼠标 Y 坐标
      imgOffsetX: 0, // 图像的 X 轴偏移量
      imgOffsetY: 0, // 图像的 Y 轴偏移量
      isZoomed: false,
      markLabel: [],
    };
  },
  mounted() {
    this.initCanvas(); // 初始化画布上下文
    this.loadImage(); // 加载图像资源
    // 添加鼠标滚轮事件监听
    const canvas = document.getElementById("myCanvas");
    canvas.addEventListener("wheel", this.handleWheel, { passive: false });
    canvas.addEventListener("mousedown", this.handleMouseDown);
    canvas.addEventListener("mousemove", this.handleMouseMove);
    canvas.addEventListener("mouseup", this.handleMouseUp);
    canvas.addEventListener("mouseleave", this.handleMouseUp); // 当鼠标离开画布时也停止拖拽
  },
  methods: {
    addRectangleList() {
      this.markLabel = [
        {
          rect: "50,60,150,160", // 矩形1：位于图像左上部分
          point0: "75,80", // 可选：矩形内的一个点
          polygon: {
            // 可选：矩形内的一个多边形
            points: "70,70,100,100,130,70",
          },
        },
        {
          rect: "200,100,300,200", // 矩形2：位于图像中央偏左
          point0: "220,120", // 矩形内的一个点
        },
        {
          rect: "400,150,500,250", // 矩形3：位于图像中央偏右
          point0: "420,170", // 矩形内的一个点
        },
        {
          rect: "600,200,700,300", // 矩形4：位于图像右下部分
          point0: "620,220", // 矩形内的一个点
        },
        {
          rect: "800,300,900,400", // 矩形5：靠近图像右边缘
          point0: "820,320", // 矩形内的一个点
        },
      ];

      this.addRectangles();
    },
    handleWheel(event) {
      event.preventDefault(); // 阻止默认行为（页面滚动）

      // 计算鼠标相对于画布的位置
      const rect = event.target.getBoundingClientRect();
      const mouseX = event.clientX - rect.left;
      const mouseY = event.clientY - rect.top;

      // 保存当前的中心点坐标
      const oldScale = this.scaleNum;
      const oldCenterX = this.imgX;
      const oldCenterY = this.imgY;

      // 根据滚轮方向调整缩放比例
      if (event.deltaY < 0) {
        this.scaleNum *= 1.1; // 放大
      } else {
        this.scaleNum /= 1.1; // 缩小
        if (this.scaleNum < 0.1) this.scaleNum = 0.1;
      }

      // 计算新的中心点坐标，以确保鼠标位置不变
      this.imgX = mouseX + (oldCenterX - mouseX) * (this.scaleNum / oldScale);
      this.imgY = mouseY + (oldCenterY - mouseY) * (this.scaleNum / oldScale);
      this.canvasInfo(); // 更新画布内容
    },

    originalSize() {
      this.scaleNum = 1;
      this.imgOffsetX = 0;
      this.imgOffsetY = 0;
      this.canvasInfo();
      this.isFit = false;
      this.isOrg = true;
      this.isZoomed = false;
    },

    // ... 其他方法 ...

    // 初始化画布并获取绘图上下文
    initCanvas() {
      this.canvas = document.getElementById("myCanvas");
      this.ctx = this.canvas.getContext("2d");
    },
    // 加载图像资源，并设置加载完成后的回调函数
    loadImage() {
      this.img = new Image();
      this.img.src = this.imgSrc;
      this.img.onload = () => {
        this.maxW = this.img.width; // 获取原始图像宽度
        this.maxH = this.img.height; // 获取原始图像高度
        this.canvasInfo(); // 图像加载完成后立即刷新画布信息
      };
    },
    // 根据用户选择更新当前绘制形状类型
    selectShape(shape) {
      this.selectedShape = shape;
    },
    // 将缩放比例重置为100%，即原始尺寸
    originalSize() {
      this.scaleNum = 1;
      this.canvasInfo(); // 更新画布以反映新的缩放比例
    },
    // 调整缩放比例使图像适应画布大小
    fitToCanvas() {
      this.scaleNum = this.canvasHeight / this.img.height;
      this.canvasInfo(); // 更新画布以反映新的缩放比例
    },
    // 减小缩放比例
    decreaseScale() {
      this.scaleNum -= 0.1;
      if (this.scaleNum < 0.1) this.scaleNum = 0.1; // 确保最小缩放比例不低于10%
      this.canvasInfo(); // 更新画布以反映新的缩放比例
    },
    // 增大缩放比例
    increaseScale() {
      this.scaleNum += 0.1;
      this.canvasInfo(); // 更新画布以反映新的缩放比例
    },
    // 清除并重新绘制整个画布内容
    canvasInfo() {
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.drawImage(); // 重新绘制图像
      this.drawShapes(); // 重新绘制所有形状
      this.addRectangles(); //绘制矩形群
    },
    // 在画布上绘制图像，根据当前缩放比例调整图像大小
    drawImage() {
      const w = this.maxW * this.scaleNum;
      const h = this.maxH * this.scaleNum;
      this.ctx.drawImage(
        this.img,
        this.imgX - w / 2 + this.imgOffsetX,
        this.imgY - h / 2 + this.imgOffsetY,
        w,
        h
      );
    },
    // 遍历所有形状并调用对应的绘制方法
    drawShapes() {
      this.shapes.forEach((shape) => {
        switch (shape.type) {
          case "rect":
            this.drawRect(shape);
            break;
          case "circle":
            this.drawCircle(shape);
            break;
          case "line":
            this.drawLine(shape);
            break;
          case "point":
            this.drawPoint(shape);
            break;
          case "polygon":
            this.drawPolygon(shape.points);
            break;
        }
      });
    },
    //添加矩形体
    addRectangles() {
      this.markLabel.forEach((i) => {
        this.drawRectList(i.rect);
      });
    },
    // 绘制矩形
    drawRect({ x, y, width, height }) {
      const scaledWidth = width * this.scaleNum;
      const scaledHeight = height * this.scaleNum;
      const scaledX =
        this.imgX -
        (this.maxW * this.scaleNum) / 2 +
        x * this.scaleNum +
        this.imgOffsetX;
      const scaledY =
        this.imgY -
        (this.maxH * this.scaleNum) / 2 +
        y * this.scaleNum +
        this.imgOffsetY;
      this.ctx.strokeRect(scaledX, scaledY, scaledWidth, scaledHeight);
    },
    //绘制矩形
    drawRectList(rectStr) {
      if (!rectStr) return;

      // 解析 rect 字符串为数字数组
      const [x1, y1, x2, y2] = rectStr.split(",").map(Number);

      // 计算矩形的宽度和高度
      const width = Math.abs(x2 - x1);
      const height = Math.abs(y2 - y1);

      // 计算矩形左上角的坐标
      const x = Math.min(x1, x2);
      const y = Math.min(y1, y2);

      // 应用缩放和平移
      const scaledWidth = width * this.scaleNum;
      const scaledHeight = height * this.scaleNum;
      const scaledX =
        this.imgX -
        (this.maxW * this.scaleNum) / 2 +
        x * this.scaleNum +
        this.imgOffsetX;
      const scaledY =
        this.imgY -
        (this.maxH * this.scaleNum) / 2 +
        y * this.scaleNum +
        this.imgOffsetY;

      // 设置绘图样式
      this.ctx.strokeStyle = "#FF0000"; // 红色边框
      this.ctx.lineWidth = 2;

      // 绘制矩形
      this.ctx.strokeRect(scaledX, scaledY, scaledWidth, scaledHeight);
    },

    // 绘制圆形
    drawCircle({ cx, cy, r }) {
      const scaledR = r * this.scaleNum;
      const scaledCx =
        this.imgX -
        (this.maxW * this.scaleNum) / 2 +
        cx * this.scaleNum +
        this.imgOffsetX;
      const scaledCy =
        this.imgY -
        (this.maxH * this.scaleNum) / 2 +
        cy * this.scaleNum +
        this.imgOffsetY;
      this.ctx.strokeStyle = "pink";

      this.ctx.beginPath();
      this.ctx.arc(scaledCx, scaledCy, scaledR, 0, Math.PI * 2);
      this.ctx.stroke();
    },
    // 绘制直线
    drawLine({ startX, startY, endX, endY }) {
      const scaledStartX =
        this.imgX -
        (this.maxW * this.scaleNum) / 2 +
        startX * this.scaleNum +
        this.imgOffsetX;
      const scaledStartY =
        this.imgY -
        (this.maxH * this.scaleNum) / 2 +
        startY * this.scaleNum +
        this.imgOffsetY;
      const scaledEndX =
        this.imgX -
        (this.maxW * this.scaleNum) / 2 +
        endX * this.scaleNum +
        this.imgOffsetX;
      const scaledEndY =
        this.imgY -
        (this.maxH * this.scaleNum) / 2 +
        endY * this.scaleNum +
        this.imgOffsetY;
      this.ctx.beginPath();
      this.ctx.moveTo(scaledStartX, scaledStartY);
      this.ctx.lineTo(scaledEndX, scaledEndY);
      this.ctx.stroke();
    },
    // 绘制点
    drawPoint({ x, y }) {
      const scaledX =
        this.imgX -
        (this.maxW * this.scaleNum) / 2 +
        x * this.scaleNum +
        this.imgOffsetX;
      const scaledY =
        this.imgY -
        (this.maxH * this.scaleNum) / 2 +
        y * this.scaleNum +
        this.imgOffsetY;
      this.ctx.strokeStyle = "pink";

      this.ctx.fillRect(scaledX, scaledY, 3, 3); // 绘制一个小方块作为点
    },
    // 绘制多边形
    drawPolygon(points) {
      this.ctx.beginPath();
      const firstPoint = points[0];
      console.log("points", points);
      console.log("firstPoint", firstPoint);
      this.ctx.moveTo(
        this.imgX -
          (this.maxW * this.scaleNum) / 2 +
          firstPoint.x * this.scaleNum +
          this.imgOffsetX,
        this.imgY -
          (this.maxH * this.scaleNum) / 2 +
          firstPoint.y * this.scaleNum +
          this.imgOffsetY
      );
      points.slice(1).forEach(({ x, y }) => {
        this.ctx.lineTo(
          this.imgX -
            (this.maxW * this.scaleNum) / 2 +
            x * this.scaleNum +
            this.imgOffsetX,
          this.imgY -
            (this.maxH * this.scaleNum) / 2 +
            y * this.scaleNum +
            this.imgOffsetY
        );
      });
      this.ctx.strokeStyle = "red";

      this.ctx.closePath();
      this.ctx.stroke();
    },
    // 添加一个新形状到形状数组，并刷新画布
    addShape(shapeData) {
      this.shapes.push(shapeData);
      this.drawShapes(shapeData);
      this.canvasInfo();
    },
    // 示例方法：添加一个矩形
    addRectangle() {
      const rect = { type: "rect", x: 50, y: 50, width: 100, height: 50 };
      this.addShape(rect);
    },
    // 示例方法：添加一个圆形
    addCircle() {
      const circle = { type: "circle", cx: 200, cy: 200, r: 50 };
      this.addShape(circle);
    },
    // 示例方法：添加一条线
    addLine() {
      const line = {
        type: "line",
        startX: 100,
        startY: 100,
        endX: 200,
        endY: 200,
      };
      this.addShape(line);
    },
    // 示例方法：添加一个点
    addPoint() {
      const point = { type: "point", x: 300, y: 200 };
      this.addShape(point);
    },
    // 示例方法：添加一个多边形
    addPolygon() {
      const polygon = {
        type: "polygon",
        points: [
          { x: 100, y: 200 },
          { x: 120, y: 120 },
          { x: 100, y: 200 },
          { x: 222, y: 352 },
          { x: 122, y: 150 },
        ],
      };
      this.addShape(polygon);
    },
    handleMouseDown(event) {
      if (this.isImageUnderMouse(event)) {
        this.isDragging = true;
        this.dragStartX = event.clientX;
        this.dragStartY = event.clientY;

        // 防止默认行为（如文本选中）
        event.preventDefault();
      }
    },
    redrawRectangles() {
      const ctx = this.ctx;

      // 设置绘图样式
      ctx.strokeStyle = "#FF0000"; // 红色边框
      ctx.lineWidth = 2;

      // 清除画布
      ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

      // 遍历所有矩形标注并绘制
      this.markLabel.forEach((item) => {
        if (item.rect) {
          // 解析 rect 字符串为数字数组
          const [x1, y1, x2, y2] = item.rect.split(",").map(Number);

          // 计算矩形的宽度和高度
          const width = Math.abs(x2 - x1);
          const height = Math.abs(y2 - y1);

          // 计算矩形左上角的坐标
          const x = Math.min(x1, x2);
          const y = Math.min(y1, y2);

          // 应用缩放和平移
          const scaledWidth = width * this.scaleNum;
          const scaledHeight = height * this.scaleNum;
          const scaledX =
            this.imgX -
            (this.maxW * this.scaleNum) / 2 +
            x * this.scaleNum +
            this.imgOffsetX;
          const scaledY =
            this.imgY -
            (this.maxH * this.scaleNum) / 2 +
            y * this.scaleNum +
            this.imgOffsetY;

          // 绘制矩形
          ctx.strokeRect(scaledX, scaledY, scaledWidth, scaledHeight);
        }
      });
    },
    handleMouseMove(event) {
      if (this.isDragging) {
        const dx = event.clientX - this.dragStartX;
        const dy = event.clientY - this.dragStartY;

        this.imgOffsetX += dx;
        this.imgOffsetY += dy;

        this.dragStartX = event.clientX;
        this.dragStartY = event.clientY;
        this.redrawRectangles();
        this.canvasInfo(); // 更新画布内容
      }
    },

    handleMouseUp() {
      this.isDragging = false;
    },

    isImageUnderMouse(event) {
      // 计算鼠标相对于画布的位置
      const rect = event.target.getBoundingClientRect();
      const mouseX = event.clientX - rect.left;
      const mouseY = event.clientY - rect.top;

      // 判断鼠标位置是否在图像内
      const w = this.maxW * this.scaleNum;
      const h = this.maxH * this.scaleNum;
      const imgLeft = this.imgX - w / 2 + this.imgOffsetX;
      const imgTop = this.imgY - h / 2 + this.imgOffsetY;

      return (
        mouseX >= imgLeft &&
        mouseX <= imgLeft + w &&
        mouseY >= imgTop &&
        mouseY <= imgTop + h
      );
    },
  },
};
</script> -->

<script setup>
import { onMounted, ref } from "vue";
const canvas = ref(null);
const scaleNum = ref(1); // 初始缩放比例为100%
const shapes = ref([]); // 存储所有绘制的形状数据
const imgSrc = ref(
  "https://file.51pptmoban.com/d/file/2024/07/28/4b668a6fd46160f0a90ccbc9c4f31adc.jpg"
); // 图像源路径，请替换为实际图片URL
const imgX = ref(600); // 图像中心点 X 坐标（默认居中）
const img = ref(null);
const ctx = ref(null);
const imgY = ref(400); // 图像中心点 Y 坐标（默认居中）
const canvasWidth = ref(1200); // 画布宽度
const canvasHeight = ref(800); // 画布高度
const isDragging = ref(false); // 标记是否正在拖拽
const dragStartX = ref(0); // 拖拽开始时的鼠标 X 坐标
const dragStartY = ref(0); // 拖拽开始时的鼠标 Y 坐标
const imgOffsetX = ref(0); // 图像的 X 轴偏移量
const imgOffsetY = ref(0); // 图像的 Y 轴偏移量
const isZoomed = ref(false);
const markLabel = ref([]); //多矩形
const maxW = ref();
const maxH = ref();
const isFit = ref(false);
const isOrg = ref(false);
onMounted(() => {
  initCanvas(); // 初始化画布上下文
  loadImage(); // 加载图像资源
  // 添加鼠标滚轮事件监听
  const canvas = document.getElementById("myCanvas");
  canvas.addEventListener("wheel", handleWheel, { passive: false });
  canvas.addEventListener("mousedown", handleMouseDown);
  canvas.addEventListener("mousemove", handleMouseMove);
  canvas.addEventListener("mouseup", handleMouseUp);
  canvas.addEventListener("mouseleave", handleMouseUp); // 当鼠标离开画布时也停止拖拽
});

function addRectangleList() {
  markLabel.value = [
    {
      rect: "50,60,150,160", // 矩形1：位于图像左上部分
      point0: "75,80", // 可选：矩形内的一个点
      polygon: {
        // 可选：矩形内的一个多边形
        points: "70,70,100,100,130,70",
      },
    },
    {
      rect: "200,100,300,200", // 矩形2：位于图像中央偏左
      point0: "220,120", // 矩形内的一个点
    },
    {
      rect: "400,150,500,250", // 矩形3：位于图像中央偏右
      point0: "420,170", // 矩形内的一个点
    },
    {
      rect: "600,200,700,300", // 矩形4：位于图像右下部分
      point0: "620,220", // 矩形内的一个点
    },
    {
      rect: "800,300,900,400", // 矩形5：靠近图像右边缘
      point0: "820,320", // 矩形内的一个点
    },
  ];

  addRectangles();
}

function handleWheel(event) {
  event.preventDefault(); // 阻止默认行为（页面滚动）

  // 计算鼠标相对于画布的位置
  const rect = event.target.getBoundingClientRect();
  const mouseX = event.clientX - rect.left;
  const mouseY = event.clientY - rect.top;

  // 保存当前的中心点坐标
  const oldScale = scaleNum.value;
  const oldCenterX = imgX.value;
  const oldCenterY = imgY.value;

  // 根据滚轮方向调整缩放比例
  if (event.deltaY < 0) {
    scaleNum.value *= 1.1; // 放大
  } else {
    scaleNum.value /= 1.1; // 缩小
    if (scaleNum.value < 0.1) scaleNum.value = 0.1;
  }

  // 计算新的中心点坐标，以确保鼠标位置不变
  imgX.value = mouseX + (oldCenterX - mouseX) * (scaleNum.value / oldScale);
  imgY.value = mouseY + (oldCenterY - mouseY) * (scaleNum.value / oldScale);
  canvasInfo(); // 更新画布内容
}

function originalSize() {
  scaleNum.value = 1;
  imgOffsetX.value = 0;
  imgOffsetY.value = 0;
  canvasInfo();
  isFit.value = false;
  isOrg.value = true;
  isZoomed.value = false;
}

// 初始化画布并获取绘图上下文
function initCanvas() {
  canvas.value = document.getElementById("myCanvas");
  ctx.value = canvas.value.getContext("2d");
}

// 加载图像资源，并设置加载完成后的回调函数
function loadImage() {
  img.value = new Image();
  img.value.src = imgSrc.value;
  img.value.onload = () => {
    maxW.value = img.value.width; // 获取原始图像宽度
    maxH.value = img.value.height; // 获取原始图像高度
    canvasInfo(); // 图像加载完成后立即刷新画布信息
  };
}


// 调整缩放比例使图像适应画布大小
function fitToCanvas() {
  scaleNum.value = canvasHeight.value / img.value.height;
  canvasInfo(); // 更新画布以反映新的缩放比例
}

// 减小缩放比例
function decreaseScale() {
  scaleNum.value -= 0.1;
  if (scaleNum.value < 0.1) scaleNum.value = 0.1; // 确保最小缩放比例不低于10%
  canvasInfo(); // 更新画布以反映新的缩放比例
}

// 增大缩放比例
function increaseScale() {
  scaleNum.value += 0.1;
  canvasInfo(); // 更新画布以反映新的缩放比例
}

// 清除并重新绘制整个画布内容
function canvasInfo() {
  ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
  drawImage(); // 重新绘制图像
  drawShapes(); // 重新绘制所有形状
  addRectangles(); //绘制矩形群
}
// 在画布上绘制图像，根据当前缩放比例调整图像大小
function drawImage() {
  const w = maxW.value * scaleNum.value;
  const h = maxH.value * scaleNum.value;
  ctx.value.drawImage(
    img.value,
    imgX.value - w / 2 + imgOffsetX.value,
    imgY.value - h / 2 + imgOffsetY.value,
    w,
    h
  );
}

// 遍历所有形状并调用对应的绘制方法
function drawShapes() {
  shapes.value.forEach((shape) => {
    switch (shape.type) {
      case "rect":
        drawRect(shape);
        break;
      case "circle":
        drawCircle(shape);
        break;
      case "line":
        drawLine(shape);
        break;
      case "point":
        drawPoint(shape);
        break;
      case "polygon":
        drawPolygon(shape.points);
        break;
    }
  });
}

//添加矩形体
function addRectangles() {
  markLabel.value.forEach((i) => {
    drawRectList(i.rect);
  });
}

// 绘制矩形
function drawRect({ x, y, width, height }) {
  const scaledWidth = width * scaleNum.value;
  const scaledHeight = height * scaleNum.value;
  const scaledX =
    imgX.value -
    (maxW.value * scaleNum.value) / 2 +
    x * scaleNum.value +
    imgOffsetX.value;
  const scaledY =
    imgY.value -
    (maxH.value * scaleNum.value) / 2 +
    y * scaleNum.value +
    imgOffsetY.value;
  ctx.value.strokeRect(scaledX, scaledY, scaledWidth, scaledHeight);
}
//绘制矩形
function drawRectList(rectStr) {
  if (!rectStr) return;

  // 解析 rect 字符串为数字数组
  const [x1, y1, x2, y2] = rectStr.split(",").map(Number);

  // 计算矩形的宽度和高度
  const width = Math.abs(x2 - x1);
  const height = Math.abs(y2 - y1);

  // 计算矩形左上角的坐标
  const x = Math.min(x1, x2);
  const y = Math.min(y1, y2);

  // 应用缩放和平移
  const scaledWidth = width * scaleNum.value;
  const scaledHeight = height * scaleNum.value;
  const scaledX =
    imgX.value -
    (maxW.value * scaleNum.value) / 2 +
    x * scaleNum.value +
    imgOffsetX.value;
  const scaledY =
    imgY.value -
    (maxH.value * scaleNum.value) / 2 +
    y * scaleNum.value +
    imgOffsetY.value;

  // 设置绘图样式
  ctx.value.strokeStyle = "#FF0000"; // 红色边框
  ctx.value.lineWidth = 2;

  // 绘制矩形
  ctx.value.strokeRect(scaledX, scaledY, scaledWidth, scaledHeight);
}

// 绘制圆形
function drawCircle({ cx, cy, r }) {
  const scaledR = r * scaleNum.value;
  const scaledCx =
    imgX.value -
    (maxW.value * scaleNum.value) / 2 +
    cx * scaleNum.value +
    imgOffsetX.value;
  const scaledCy =
    imgY.value -
    (maxH.value * scaleNum.value) / 2 +
    cy * scaleNum.value +
    imgOffsetY.value;
  ctx.value.strokeStyle = "pink";

  ctx.value.beginPath();
  ctx.value.arc(scaledCx, scaledCy, scaledR, 0, Math.PI * 2);
  ctx.value.stroke();
}

// 绘制直线
function drawLine({ startX, startY, endX, endY }) {
  const scaledStartX =
    imgX.value -
    (maxW.value * scaleNum.value) / 2 +
    startX * scaleNum.value +
    imgOffsetX.value;
  const scaledStartY =
    imgY.value -
    (maxH.value * scaleNum.value) / 2 +
    startY * scaleNum.value +
    imgOffsetY.value;
  const scaledEndX =
    imgX.value -
    (maxW.value * scaleNum.value) / 2 +
    endX * scaleNum.value +
    imgOffsetX.value;
  const scaledEndY =
    imgY.value -
    (maxH.value * scaleNum.value) / 2 +
    endY * scaleNum.value +
    imgOffsetY.value;
  ctx.value.beginPath();
  ctx.value.moveTo(scaledStartX, scaledStartY);
  ctx.value.lineTo(scaledEndX, scaledEndY);
  ctx.value.stroke();
}

// 绘制点
function drawPoint({ x, y }) {
  const scaledX =
    imgX.value -
    (maxW.value * scaleNum.value) / 2 +
    x * scaleNum.value +
    imgOffsetX.value;
  const scaledY =
    imgY.value -
    (maxH.value * scaleNum.value) / 2 +
    y * scaleNum.value +
    imgOffsetY.value;
  ctx.value.strokeStyle = "pink";

  ctx.value.fillRect(scaledX, scaledY, 3, 3); // 绘制一个小方块作为点
}

// 绘制多边形
function drawPolygon(points) {
  ctx.value.beginPath();
  const firstPoint = points[0];
  ctx.value.moveTo(
    imgX.value -
      (maxW.value * scaleNum.value) / 2 +
      firstPoint.x * scaleNum.value +
      imgOffsetX.value,
    imgY.value -
      (maxH.value * scaleNum.value) / 2 +
      firstPoint.y * scaleNum.value +
      imgOffsetY.value
  );
  points.slice(1).forEach(({ x, y }) => {
    ctx.value.lineTo(
      imgX.value -
        (maxW.value * scaleNum.value) / 2 +
        x * scaleNum.value +
        imgOffsetX.value,
      imgY.value -
        (maxH.value * scaleNum.value) / 2 +
        y * scaleNum.value +
        imgOffsetY.value
    );
  });
  ctx.value.strokeStyle = "red";

  ctx.value.closePath();
  ctx.value.stroke();
}

// 添加一个新形状到形状数组，并刷新画布
function addShape(shapeData) {
  shapes.value.push(shapeData);
  drawShapes(shapeData);
  canvasInfo();
}

// 示例方法：添加一个矩形
function addRectangle() {
  const rect = { type: "rect", x: 50, y: 50, width: 100, height: 50 };
  addShape(rect);
}
// 示例方法：添加一个圆形
function addCircle() {
  const circle = { type: "circle", cx: 200, cy: 200, r: 50 };
  addShape(circle);
}

// 示例方法：添加一条线
function addLine() {
  const line = {
    type: "line",
    startX: 100,
    startY: 100,
    endX: 200,
    endY: 200,
  };
  addShape(line);
}

// 示例方法：添加一个点
function addPoint() {
  const point = { type: "point", x: 300, y: 200 };
  addShape(point);
}

// 示例方法：添加一个多边形
function addPolygon() {
  const polygon = {
    type: "polygon",
    points: [
      { x: 100, y: 200 },
      { x: 120, y: 120 },
      { x: 100, y: 200 },
      { x: 222, y: 352 },
      { x: 122, y: 150 },
    ],
  };
  addShape(polygon);
}

function handleMouseDown(event) {
  if (isImageUnderMouse(event)) {
    isDragging.value = true;
    dragStartX.value = event.clientX;
    dragStartY.value = event.clientY;

    // 防止默认行为（如文本选中）
    event.preventDefault();
  }
}
//移动
function redrawRectangles() {
  // 设置绘图样式
  // ctx.value.strokeStyle = "#FF0000"; // 红色边框
  // ctx.value.lineWidth = 2;

  // 清除画布
  ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);

  // 遍历所有矩形标注并绘制
  markLabel.value.forEach((item) => {
    if (item.rect) {
      // 解析 rect 字符串为数字数组
      const [x1, y1, x2, y2] = item.rect.split(",").map(Number);

      // 计算矩形的宽度和高度
      const width = Math.abs(x2 - x1);
      const height = Math.abs(y2 - y1);

      // 计算矩形左上角的坐标
      const x = Math.min(x1, x2);
      const y = Math.min(y1, y2);

      // 应用缩放和平移
      const scaledWidth = width * scaleNum.value;
      const scaledHeight = height * scaleNum.value;
      const scaledX =
        imgX.value -
        (maxW.value * scaleNum.value) / 2 +
        x * scaleNum.value +
        imgOffsetX.value;
      const scaledY =
        imgY.value -
        (maxH.value * scaleNum.value) / 2 +
        y * scaleNum.value +
        imgOffsetY.value;

      // 绘制矩形
      ctx.value.strokeRect(scaledX, scaledY, scaledWidth, scaledHeight);
    }
  });
}

function handleMouseMove(event) {
  if (isDragging.value) {
    const dx = event.clientX - dragStartX.value;
    const dy = event.clientY - dragStartY.value;

    imgOffsetX.value += dx;
    imgOffsetY.value += dy;

    dragStartX.value = event.clientX;
    dragStartY.value = event.clientY;
    redrawRectangles();
    canvasInfo(); // 更新画布内容
  }
}

function handleMouseUp() {
  isDragging.value = false;
}

function isImageUnderMouse(event) {
  // 计算鼠标相对于画布的位置
  const rect = event.target.getBoundingClientRect();
  const mouseX = event.clientX - rect.left;
  const mouseY = event.clientY - rect.top;

  // 判断鼠标位置是否在图像内
  const w = maxW.value * scaleNum.value;
  const h = maxH.value * scaleNum.value;
  const imgLeft = imgX.value - w / 2 + imgOffsetX.value;
  const imgTop = imgY.value - h / 2 + imgOffsetY.value;

  return (
    mouseX >= imgLeft &&
    mouseX <= imgLeft + w &&
    mouseY >= imgTop &&
    mouseY <= imgTop + h
  );
}
</script>
<style scoped>
/* 样式规则 */
.image-annotation {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.control-panel {
  margin-bottom: 20px;
}
.scale-controls {
  margin-top: 10px;
}
#myCanvas {
  border: 1px solid #ccc; /* 为画布添加边框 */
}
</style>
